package com.duyutian.aop;

import com.duyutian.common.CusAccessObjectUtil;
import com.duyutian.controller.hiwodytController.service.LogService;
import com.duyutian.domain.Loger;
import com.duyutian.util.RedisTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

/**
 * Created by dyt on 2018/10/20.
 */
//博客访客记录
@Component
public class IndexLogIntercept implements HandlerInterceptor {
    @Autowired
    private RedisTools redisTools;
    @Autowired
    private LogService logService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if(!redisTools.hasIp(CusAccessObjectUtil.getIpAddress(httpServletRequest))){
            //redis 中初始化访客
            ArrayList<Loger> ips = redisTools.getLogs();
            Loger loger1 = new Loger();
            loger1.setIp(CusAccessObjectUtil.getIpAddress(httpServletRequest));
            ips.add(loger1);
            redisTools.addLogs(loger1);
        }
        //在数据库跟新该访客记录
        logService.setLog(CusAccessObjectUtil.getIpAddress(httpServletRequest));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
